/**
 * 用户认证服务
 * 基于后端认证接口实现
 */

import http, { setToken, clearToken } from './api.js'

// 用户认证服务
const authService = {
    /**
     * 用户注册
     * POST /api/v1/auth/register
     * @param {Object} userData - 注册数据
     * @param {String} userData.username - 用户名
     * @param {String} userData.email - 邮箱
     * @param {String} userData.emailCode - 邮箱验证码
     * @param {String} userData.password - 密码
     * @param {String} userData.phone - 手机号（可选）
     * @param {String} userData.realName - 真实姓名（可选）
     * @param {String} userData.role - 角色：customer | merchant（可选，默认customer）
     * @param {Object} userData.merchantInfo - 商家信息（role=merchant时必填）
     */
    register: async (userData) => {
        try {
            // 构建请求参数
            const requestData = {
                username: userData.username,
                email: userData.email,
                code: userData.emailCode || userData.code,  // 兼容两种命名
                password: userData.password,
                phone: userData.phone,
                realName: userData.realName
            }

            // 如果指定了角色，添加到请求中
            if (userData.role) {
                requestData.role = userData.role
            }

            // 如果是商家注册，添加商家信息
            if (userData.role === 'merchant' && userData.merchantInfo) {
                requestData.merchantInfo = {
                    name: userData.merchantInfo.name,
                    address: userData.merchantInfo.address,
                    phone: userData.merchantInfo.phone,
                    description: userData.merchantInfo.description || ''
                }
            }

            console.log('📝 注册请求数据:', requestData)

            const response = await http.post('/auth/register', requestData, {
                needAuth: false,
                showLoading: true,
                loadingText: '注册中...'
            })

            // 注册成功后自动保存token
            if (response.data && response.data.token) {
                setToken(response.data.token)

                // 保存用户信息到本地存储
                if (response.data.user) {
                    uni.setStorageSync('user_info', response.data.user)
                    console.log('✅ 注册成功，用户角色:', response.data.user.role)
                }
            }

            return response
        } catch (error) {
            console.error('用户注册失败:', error)
            throw error
        }
    },

    /**
     * 用户登录
     * POST /api/v1/auth/login
     */
    login: async (credentials) => {
        try {
            const response = await http.post('/auth/login', {
                username: credentials.username,
                password: credentials.password,
                remember: credentials.remember || true
            }, {
                needAuth: false,
                showLoading: true,
                loadingText: '登录中...'
            })

            // 登录成功后保存token和用户信息
            if (response.data && response.data.token) {
                setToken(response.data.token)

                // 保存用户信息到本地存储
                if (response.data.user) {
                    // 临时方案：如果后端还没返回role，根据用户名判断
                    // 如果用户名包含 'merchant_'，自动设置为商家
                    if (!response.data.user.role && credentials.username.includes('merchant_')) {
                        response.data.user.role = 'merchant'
                        // 从用户名推断商家ID（merchant_yuweixian -> 1, merchant_chuanweiguan -> 2, 等）
                        const merchantMap = {
                            'merchant_yuweixian': 1,
                            'merchant_chuanweiguan': 2,
                            'merchant_xiangjige': 3,
                            'merchant_shenyeshitang': 4
                        }
                        response.data.user.merchantId = merchantMap[credentials.username] || null
                    }

                    uni.setStorageSync('user_info', response.data.user)
                }
            }

            return response
        } catch (error) {
            console.error('用户登录失败:', error)
            throw error
        }
    },

    /**
     * 获取用户信息
     * GET /api/v1/auth/profile
     */
    getProfile: async () => {
        try {
            const response = await http.get('/auth/profile', {}, {
                needAuth: true
            })

            // 更新本地存储的用户信息
            if (response.data) {
                uni.setStorageSync('user_info', response.data)
            }

            return response
        } catch (error) {
            console.error('获取用户信息失败:', error)
            throw error
        }
    },

    /**
     * 更新用户信息
     * PUT /api/v1/auth/profile
     */
    updateProfile: async (profileData) => {
        try {
            const response = await http.put('/auth/profile', {
                realName: profileData.realName,
                phone: profileData.phone,
                gender: profileData.gender,
                avatar: profileData.avatar
            }, {
                needAuth: true,
                showLoading: true,
                loadingText: '更新中...'
            })

            // 更新本地存储的用户信息
            if (response.data) {
                uni.setStorageSync('user_info', response.data)
            }

            return response
        } catch (error) {
            console.error('更新用户信息失败:', error)
            throw error
        }
    },

    /**
     * 用户登出
     */
    logout: async () => {
        try {
            // 清除本地存储
            clearToken()
            uni.removeStorageSync('user_info')

            console.log('用户已登出，清除本地数据')
            return true
        } catch (error) {
            console.error('登出失败:', error)
            return false
        }
    },

    /**
     * 检查登录状态
     */
    checkLoginStatus: () => {
        const token = uni.getStorageSync('jwt_token')
        const userInfo = uni.getStorageSync('user_info')

        return {
            isLoggedIn: !!token,
            token,
            userInfo
        }
    },

    /**
     * 获取本地存储的用户信息
     */
    getLocalUserInfo: () => {
        return uni.getStorageSync('user_info') || null
    },

    /**
     * 获取用户角色
     */
    getUserRole: () => {
        const userInfo = uni.getStorageSync('user_info')
        return userInfo ? userInfo.role : null
    },

    /**
     * 检查是否是商家
     */
    isMerchant: () => {
        const userInfo = uni.getStorageSync('user_info')
        return userInfo && userInfo.role === 'merchant'
    },

    /**
     * 获取商家ID
     */
    getMerchantId: () => {
        const userInfo = uni.getStorageSync('user_info')
        return userInfo && userInfo.merchantId ? userInfo.merchantId : null
    },

    /**
     * 验证注册数据
     */
    validateRegisterData: (data) => {
        const errors = []

        if (!data.username || data.username.trim() === '') {
            errors.push('用户名不能为空')
        } else if (data.username.length < 3) {
            errors.push('用户名至少3个字符')
        }

        if (!data.email || data.email.trim() === '') {
            errors.push('邮箱不能为空')
        } else {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
            if (!emailRegex.test(data.email)) {
                errors.push('请输入正确的邮箱格式')
            }
        }

        if (!data.password || data.password.trim() === '') {
            errors.push('密码不能为空')
        } else if (data.password.length < 6) {
            errors.push('密码至少6个字符')
        }

        if (!data.phone || data.phone.trim() === '') {
            errors.push('手机号不能为空')
        } else {
            const phoneRegex = /^1[3-9]\d{9}$/
            if (!phoneRegex.test(data.phone)) {
                errors.push('请输入正确的手机号')
            }
        }

        if (!data.realName || data.realName.trim() === '') {
            errors.push('真实姓名不能为空')
        }

        return {
            isValid: errors.length === 0,
            errors
        }
    },

    /**
     * 验证登录数据
     */
    validateLoginData: (data) => {
        const errors = []

        if (!data.username || data.username.trim() === '') {
            errors.push('用户名不能为空')
        }

        if (!data.password || data.password.trim() === '') {
            errors.push('密码不能为空')
        }

        return {
            isValid: errors.length === 0,
            errors
        }
    },

    /**
     * 发送邮箱验证码
     * POST /api/v1/auth/email/send-code
     * @param {Object} data - { email, type: 'register' | 'reset_password' | 'change_email' }
     */
    sendEmailCode: async (data) => {
        try {
            console.log('📧 发送邮箱验证码:', data)

            const response = await http.post('/auth/email/send-code', {
                email: data.email,
                type: data.type || 'register'
            }, {
                needAuth: false,
                showLoading: false
            })

            console.log('✅ 验证码发送成功')
            return response
        } catch (error) {
            console.error('发送邮箱验证码失败:', error)
            throw error
        }
    },

    /**
     * 验证邮箱验证码
     * POST /api/v1/auth/email/verify-code
     * @param {Object} data - { email, code, type }
     */
    verifyEmailCode: async (data) => {
        try {
            console.log('🔍 验证邮箱验证码:', data)

            const response = await http.post('/auth/email/verify-code', {
                email: data.email,
                code: data.code,
                type: data.type || 'register'
            }, {
                needAuth: false,
                showLoading: false
            })

            console.log('✅ 验证码验证成功')
            return response
        } catch (error) {
            console.error('验证邮箱验证码失败:', error)
            throw error
        }
    },

    /**
     * 修改密码（已登录用户）
     * PUT /api/v1/auth/password
     * @param {Object} data - { oldPassword, newPassword }
     */
    changePassword: async (data) => {
        try {
            console.log('🔑 修改密码')

            const response = await http.put('/auth/password', {
                oldPassword: data.oldPassword,
                newPassword: data.newPassword
            }, {
                needAuth: true,
                showLoading: true,
                loadingText: '修改中...'
            })

            console.log('✅ 密码修改成功')
            return response
        } catch (error) {
            console.error('修改密码失败:', error)
            throw error
        }
    },

    /**
     * 重置密码（忘记密码）
     * POST /api/v1/auth/password/reset
     * @param {Object} data - { email, code, newPassword }
     */
    resetPassword: async (data) => {
        try {
            console.log('🔑 重置密码')

            const response = await http.post('/auth/password/reset', {
                email: data.email,
                code: data.code,
                newPassword: data.newPassword
            }, {
                needAuth: false,
                showLoading: false
            })

            console.log('✅ 密码重置成功')
            return response
        } catch (error) {
            console.error('重置密码失败:', error)
            throw error
        }
    },

    /**
     * 修改邮箱
     * PUT /api/v1/auth/email
     * @param {Object} data - { newEmail, code, password }
     */
    changeEmail: async (data) => {
        try {
            console.log('📧 修改邮箱')

            const response = await http.put('/auth/email', {
                newEmail: data.newEmail,
                code: data.code,
                password: data.password
            }, {
                needAuth: true,
                showLoading: false
            })

            console.log('✅ 邮箱修改成功')

            // 更新本地用户信息
            if (response.data) {
                uni.setStorageSync('user_info', response.data)
            }

            return response
        } catch (error) {
            console.error('修改邮箱失败:', error)
            throw error
        }
    }
}

export default authService






